<template>
  <div class="container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input style="width: 300px;" v-model="inputyan" placeholder="请输入品牌商id"></el-input>
      <el-input style="width: 300px; margin-left: 10px;" v-model="input7" placeholder="请输入品牌名称"></el-input>
      <el-button class="annu" type="primary" icon="el-icon-search" @click="searchData">查找</el-button>
      <el-button class="edit-button" icon="el-icon-edit" @click="openAddModal">添加</el-button>
      <el-button class="annu2" type="primary" icon="el-icon-download" @click="exportData">导出</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table-wrapper">
      <el-table
        :data="list"
        border
        style="width: 100%"
        :row-class-name="tableRowClassName"
        :key="page + '-' + limit"
        @sort-change="handleSortChange"
      >
        <el-table-column
          fixed
          prop="id"
          label="品牌商id"
          width="100"
          sortable="custom"
        >
        </el-table-column>
        <el-table-column
          prop="name"
          label="品牌商名称"
          width="140"
        >
        </el-table-column>
        <el-table-column
          prop="picUrl"
          label="品牌商图片"
          width="110"
        >
          <template slot-scope="scope">
            <img 
              :src="scope.row.picUrl" 
              alt="用户头像" 
              style="width: 50px; height: 50px; border-radius: 50%;"
              @error="handleImageError(scope.row)"
              @click="openImageModal(scope.row.picUrl)"
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="desc"
          label="介绍"
          width="500"
        >
        </el-table-column>
        <el-table-column
          prop="floorPrice"
          label="底价"
          width="130"
        >
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
        >
          <template slot-scope="scope">
            <el-button class="edit-button" @click="showDetail(scope.row)">编辑</el-button>
            <el-button class="edit-button" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="list.length === 0" style="text-align: center; padding: 20px;">
        暂无数据
      </div>
    </div>
    <!-- 分页区域 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 详情弹框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      title="用户详情"
      width="30%"
    >
      <p>品牌商名称</p>
      <el-input v-model="selectedUser.name" placeholder="请输入内容"></el-input>
      <p>介绍</p>
      <el-input v-model="selectedUser.desc" placeholder="请输入内容"></el-input>
      <el-upload
        class="avatar-uploader"
        action="/api/admin/storage/create"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="selectedUser.picUrl" :src="selectedUser.picUrl + '?t=' + Date.now()" class="avatar" style="width: 100px; height: 100px; border-radius: 50%;">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <p>底价</p>
      <el-input v-model="selectedUser.floorPrice" placeholder="请输入内容"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button @click="queding">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 模态框2 -->
    <el-dialog
      :visible.sync="dialogVisible1"
      title="用户详情"
      width="30%"
    >
      <p>品牌商名称</p>
      <el-input v-model="selectedUser.name" placeholder="请输入内容"></el-input>
      <p>介绍</p>
      <el-input v-model="selectedUser.desc" placeholder="请输入内容"></el-input>
      <p>额外图片</p>
      <el-upload
        class="avatar-uploader"
        action="/api/admin/storage/create"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="selectedUser.picUrl" :src="selectedUser.picUrl + '?t=' + Date.now()" class="avatar" style="width: 100px; height: 100px; border-radius: 50%;">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
      <p>底价</p>
      <el-input v-model="selectedUser.floorPrice" placeholder="请输入内容"></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button @click="addBrand">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 图片放大模态框 -->
    <el-dialog
      :visible.sync="imageDialogVisible"
      title="图片详情"
      width="40%"
    >
      <div class="image-operation">
        <el-button class="el-icon-zoom-out" style="z-index:999" @click="zoomIn"></el-button>
        <el-button class="el-icon-zoom-in" @click="zoomOut"></el-button>
        <el-button class="el-icon-full-screen" @click="resetZoom"></el-button>
        <el-button class="el-icon-refresh-left" @click="rotateLeft"></el-button>
        <el-button class="el-icon-refresh-left" @click="rotateRight"></el-button>
      </div>
      <img 
        :src="currentImageUrl" 
        alt="放大图片" 
        :style="{ transform: `scale(${scale}) rotate(${rotation}deg)` }"
      >
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="imageDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { huiyuan, searchUserList, getUserById, bianji, apiDeleteRow, createBrand } from '@/api/shangchangguanli/pinpaishangzhizao.js';
import dayjs from 'dayjs';

export default {
  data() {
    return {
      inputyan: '',
      input7: '',
      input8: '',
      list: [],
      page: 1,
      limit: 10,
      total: 0,
      sort: 'add_time',
      order: 'desc',
      dialogVisible: false,
      dialogVisible1: false,
      imageDialogVisible: false,
      selectedUser: {},
      token: localStorage.getItem('token'),
      currentImageUrl: '',
      scale: 1,
      rotation: 0,
   
      genderOptions: [
        { value: 1, label: '男' },
        { value: 2, label: '女' }
      ]
    };
  },
  created() {
    this.fetchData();
  },
  mounted() {
    const params = {
      name: this.input7,
      id: this.inputyan,
      page: this.page,
      limit: this.limit,
      sort: this.sort,
      order: this.order,
      token: this.token
    };
    huiyuan(params)
     .then((res) => {
        console.log('huiyuan 请求响应:', res);
        if (res.data && Array.isArray(res.data.list)) {
          const formattedList = res.data.list.map(item => {
            return {
              ...item,
              addTime: dayjs(item.addTime).format('YYYY-MM-DD HH:mm:ss'),
              lastLoginTime: dayjs(item.lastLoginTime).format('YYYY-MM-DD HH:mm:ss'),
              updateTime: dayjs(item.updateTime).format('YYYY-MM-DD HH:mm:ss')
            };
          });
          this.list = formattedList;
          this.total = res.data.total;
        } else {
          console.error('huiyuan 接口返回的数据格式不符合预期', res.data);
        }
      })
     .catch((error) => {
        console.error('huiyuan 请求出错:', error);
      });
  },
  methods: {
    openImageModal(url) {
      this.currentImageUrl = url;
      this.imageDialogVisible = true;
      // 重置缩放和旋转
      this.scale = 1;
      this.rotation = 0;
    },

    zoomIn() {
      this.scale += 0.1;
    },

    zoomOut() {
      if (this.scale > 0.1) {
        this.scale -= 0.1;
      }
    },

    resetZoom() {
      this.scale = 1;
    },

    rotateLeft() {
      this.rotation -= 90;
    },

    rotateRight() {
      this.rotation += 90;
    },
    formatGender(row, column, cellValue) {
      const option = this.genderOptions.find(opt => opt.value === cellValue);
      return option? option.label : '未知';
    },
    formatDate(row, column, cellValue) {
      return dayjs(cellValue).format('YYYY-MM-DD');
    },
    formatUserLevel(row, column, cellValue) {
      return this.userLevelOptions? this.userLevelOptions.find(option => option.value === cellValue)?.label || cellValue : cellValue;
    },
    formatStatus(row, column, cellValue) {
      return this.statusOptions? this.statusOptions.find(option => option.value === cellValue)?.label || cellValue : cellValue;
    },
    showDetail(row) {
      console.log('点击行的数据:', row);
      this.selectedUser = { ...row };
      this.dialogVisible = true;
    },
    openAddModal() {

      this.selectedUser = {
        name: '',
        desc: '',
        floorPrice: '',
        picUrl: ''
      };
      this.dialogVisible1 = true;
    },
    addBrand() {
      const payload = {
        desc: this.selectedUser.desc,
        floorPrice: this.selectedUser.floorPrice,
        name: this.selectedUser.name,
        picUrl: this.selectedUser.picUrl,
      };

      createBrand(payload)
       .then((res) => {
          console.log('添加品牌商响应:', res);
          if (res.data && res.data.code === 200) {
            this.$message.success('品牌商添加成功');
            this.dialogVisible1 = false;
            this.fetchData(); 
          } else {
            this.$message.success('品牌商添加成功');
            this.dialogVisible1 = false;
            this.fetchData(); 
          }
        })
       .catch((error) => {
          console.error('添加品牌商出错:', error);
          this.$message.error('添加品牌商出错，请重试');
        });
    },
    // 重置
    reset() {
      this.inputyan = '';
      this.input7 = '';
      this.input8 = '';
      this.page = 1;
      this.fetchData();
    },
    // 删除数据
    async handleDelete(row) {
      const confirmResult = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      if (confirmResult === 'confirm') {
        try {
          const deleteParams = {
            id: row.id
          };
          const res = await apiDeleteRow(deleteParams);
          console.log('删除接口返回的数据:', res);
          if (typeof res === 'object' && res.code === 200) { 
            this.$message.success('删除成功');
            await this.fetchData(); 
          } else {
            this.$message.error(`删除失败，原因：${res.errmsg || '未知错误'}`);
            await this.fetchData();
          }
        } catch (error) {
          console.error('删除数据出错:', error);
          this.$message.error('删除失败，请重试');
        }
      } else {
        this.$message.info('已取消删除');
      }
    },
    // 搜索数据
    searchData() {
      if (this.input7) {
        this.getUserById();
      } else {
        this.page = 1;
        this.fetchData();
      }
    },
    async fetchData() {
      const params = {
        name: this.input7,
        id: this.inputyan,
        mobile: this.input8,
        page: this.page,
        limit: this.limit,
        sort: this.sort,
        order: this.order,
        token: this.token
      };
      console.log('请求参数:', params);
      try {
        const res = await searchUserList(params);
        console.log('searchUserList 请求响应:', res);
        if (res.data && Array.isArray(res.data.list)) {
          const formattedList = res.data.list.map(item => {
            return {
              ...item,
              addTime: dayjs(item.addTime).format('YYYY-MM-DD HH:mm:ss'),
              lastLoginTime: dayjs(item.lastLoginTime).format('YYYY-MM-DD HH:mm:ss'),
              updateTime: dayjs(item.updateTime).format('YYYY-MM-DD HH:mm:ss')
            };
          });
          this.list = formattedList;
          this.total = res.data.total;
        } else {
          console.error('searchUserList 接口返回的数据格式不符合预期', res.data);
        }
      } catch (error) {
        console.error('数据请求出错:', error);
      }
    },
    async getUserById() {
      if (typeof getUserById!== 'function') {
        console.error('getUserById 不是一个函数，请检查 API 引入和导出');
        return;
      }
      const params = {
        name: this.input7, 
        token: this.token
      };
      console.log('根据 name 搜索的请求参数:', params);
      console.log('传递的 name 值:', this.input7);
      try {
        const res = await getUserById(params);
        console.log('getUserById 请求响应:', res);
        if (res.data) {
          let formattedList;
          if (Array.isArray(res.data.list)) {
            formattedList = res.data.list.map(item => {
              return {
                ...item,
             
              };
            });
          } else {
            formattedList = [res.data].map(item => {
              return {
                ...item,
              };
            });
          }
          this.list = formattedList;
          this.total = formattedList.length;
        } else {
          console.error('getUserById 接口返回的数据格式不符合预期', res.data);
        }
      } catch (error) {
        console.error('根据 name 搜索数据出错:', error.response? error.response.data : error);
      }
    },
    tableRowClassName({ row, rowIndex }) {
      return rowIndex % 2 === 1? 'dark-row' : '';
    },
    handleSizeChange(newLimit) {
      this.limit = newLimit;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.page = newPage;
      this.fetchData();
    },
    async queding() {
      try {
        const { id, name, desc, floorPrice, picUrl } = this.selectedUser;
        const params = {
          id,
          name,
          desc,
          floorPrice,
          picUrl,
          token: this.token
        };
        const res = await bianji(params);
        console.log('编辑用户信息响应:', res);
        if (res.data && res.data.code === 200) {
          this.$message.success('用户信息更新成功');
          this.dialogVisible = false;
          this.fetchData(); 
        } else {
           this.$message.success('用户信息更新成功');
          this.dialogVisible = false;
          this.fetchData(); 
        }
      } catch (error) {
        console.error('编辑用户信息出错:', error);
        this.$message.error('编辑用户信息出错');
      }
    },
    exportData() {
      if (this.list.length === 0) {
        this.$message.warning('暂无数据可导出');
        return;
      }
      const headers = [
        '品牌商id', '品牌商名称', '品牌商图片', '介绍', '低价', 
      ];
      const csvContent = [headers.join(',')];

      this.list.forEach(item => {
        const row = [
          item.id,
          item.name,
          item.desc,
          item.floorPrice,
          this.formatGender(item, null, item.gender),
          this.formatDate(item, null, item.addTime),
          this.formatUserLevel(item, null, item.userLevel),
          this.formatStatus(item, null, item.status)
        ];
                csvContent.push(row.join(','));
            });
            const csvBlob = new Blob([csvContent.join('\n')], { type: 'text/csv;charset=utf-8;' });
            const csvUrl = URL.createObjectURL(csvBlob);
            const link = document.createElement('a');
            link.href = csvUrl;
            link.setAttribute('download', '用户数据.csv');
            link.click();
            URL.revokeObjectURL(csvUrl);
        },
        handleSortChange({ column, prop, order }) {
            if (prop === 'id') {
                this.sort = 'id';
                this.order = order === 'ascending'? 'asc' : 'desc';
                this.page = 1;
                this.fetchData();
            }
        },
        handleImageError(row) {
            const img = new Image();
            img.src = row.picUrl;
            img.onerror = () => {
                console.log('图片加载失败，图片路径:', row.picUrl);
                console.log('HTTP 状态码:', img.status);
            };
        },
        handleAvatarSuccess(response, file, fileList) {
            console.log('服务器返回的响应数据:', response.errno, response.data);
            try {
                if (response.errno == 0 && response.data.url) {
                    this.selectedUser.picUrl = response.data.url;
                    this.$message.success('图片上传成功');
                } else {
                    this.$message.error('图片上传成功，但未获取到正确的图片路径');
                }
            } catch (error) {
                console.error('处理上传响应数据时出现异常:', error);
                this.$message.error('图片上传成功，但处理响应数据时出现异常');
            }
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isPNG = file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG && !isPNG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG || isPNG && isLt2M;
        }
    }
};
</script>

<style scoped>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.container {
  display: flex;
  flex-direction: column;
  padding: 10px;
}

.search-area {
  display: flex;
  align-items: center;
  padding-bottom: 10px;
}

.el-input--small .el-input__inner {
  height: 47px;
  line-height: 32px;
}

.table-wrapper {
  flex: 1;
  overflow-y: auto;
}

.el-button--small {
  padding: 14px 36px;
  font-size: 12px;
  border-radius: 3px;
}

.pagination-area {
  padding: 10px 0;
  display: flex;
  justify-content: flex-end;
}

.el-input__inner {
  height: 50px;
  line-height: 50px;
}

.dark-row {
  background-color: #f5f5f5;
}

.cell {
  font-size: 18px;
}
.archive-button {
  background-color: #fff; 
  color: #f56c6c; 
  border: 1px solid #f56c6c; 
  padding: 6px 12px; 
  border-radius: 4px; 
  display: inline-flex; 
  align-items: center; 
  justify-content: center; 
  transition: all 0.3s; 
}

.archive-button:hover {
  background-color: #f56c6c; 
  color: #fff; 
}
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
    img {
    border-style: none;
    width: 283px;
}
img {
    border-style: none;
    width: 283px;
}
.el-dialog__body {
    padding: 30px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
    width: 80px;
} 
.image-operation{
position: absolute;
bottom: 0px;
}
.edit-button{
  background: #409EFF;
  color: #ffffff;
}
</style>